﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Net.Mail;
using System.Net.Mime;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace ArchSoft
{
    public partial class MailFrm : Form
    {
        private string _projectPath;
        private string[] _attachFiles;
        private string[] _attachFiles1;

        string _nameFrom;
        T3VForm _form;
        MDIChildForm _childForm;

        public string ProjectPath
        {
            set { _projectPath = value; }
        }

        public string[] AttachFiles
        {
            set { _attachFiles = value; }
        }

        public MailFrm()
        {
            InitializeComponent();
        }

        public void setForm(T3VForm form)
        {
            _form = form;
        }

        public void setChildForm(MDIChildForm childform)
        {
            _childForm = childform;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (!bind)
                {
                    //MessageBox.Show("You must bind xref beforce send mail");
                    MessageBox.Show("Bạn phải ràng buộc xref trước khi gửi thư ");
                    button5.Focus();
                    return;
                }

                string _from = txtFrom.Text;
                string _to = txtTo.Text;


                bool bTest = ValidateEmailAddress(_from);

                if (bTest == false)
                    //MessageBox.Show("Invalid recipient email address: " + _from);
                    MessageBox.Show("Địa chỉ email của người nhận không hợp lệ : " + _from);

                bool bTest1 = ValidateEmailAddress(_to);

                if (bTest1 == false)
                    //MessageBox.Show("Invalid recipient email address: " + _to);
                    MessageBox.Show("Địa chỉ email của người nhận không hợp lệ: " + _to);



                MailMessage email = new MailMessage();

                email.From = new MailAddress(_from, _nameFrom);

                email.To.Add(_to);


                email.Subject = txtSub.Text;
                email.Body = txtBody.Text;
                email.Priority = MailPriority.Normal;
                //  email.Attachments.Add(


                string[] arr1 = txtCc.Text.Split(';');
                foreach (string cc in arr1)
                {
                    if (cc != "")
                    {
                        email.CC.Add(cc);
                    }
                }

                // email.Attachments.Add(_attach);


                //foreach (string s in _attachFiles)
                //{
                //    Attachment _attach = new Attachment(s);
                //    email.Attachments.Add(_attach);
                //}

                foreach (string s in _attachFiles1)
                {
                    Attachment _attach = new Attachment(s);
                    email.Attachments.Add(_attach);
                }


                SmtpClient mail_client = new SmtpClient();
                NetworkCredential network_cdr = new NetworkCredential();
                network_cdr.UserName = "tuongtrang@trang.com.vn";
                network_cdr.Password = "1234567";

                mail_client.Host = "mail.trang.com.vn";

                mail_client.UseDefaultCredentials = false;
                mail_client.Credentials = network_cdr;
                // mail_client.EnableSsl = true;

                mail_client.Send(email);


                //MessageBox.Show("Email Sent Successfully");
                MessageBox.Show("Gửi email thành công");
                this.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        string[] arr;
        private void button2_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    OpenFileDialog of = new OpenFileDialog();
            //    of.Multiselect = true;


            //    if (of.ShowDialog() == DialogResult.OK)
            //    {
            //        arr = of.FileNames;

            //        foreach (string s in arr)
            //        {
            //            listBox1.Items.Add(Path.GetFileNameWithoutExtension(s));
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{

            //}
        }

        public bool ValidateEmailAddress(string emailAddress)
        {
            try
            {
                string TextToValidate = emailAddress;
                //                Regex expression = new Regex(@"\w+@[a-zA-Z_]+?\.[a-zA-
                //                Z]{2,3}");


                //                // test email address with expression
                //                if (expression.IsMatch(TextToValidate))
                //                {
                //                    // is valid email address
                //                    return true;
                //                }
                //                else
                //                {
                //                    // is not valid email address
                //                    return false;
                //                }

                Regex emailregex = new Regex("(?<user>[^@]+)@(?<host>.+)");
                Match m = emailregex.Match(TextToValidate);
                if (m.Success)
                {
                    // success,, so do something;
                    return true;
                }
                else
                {
                    // didn't manage to find the regular expression
                    return false;
                }

            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            ContactMail frm = new ContactMail();
            frm.ProjectPath = _projectPath;
            frm.StartPosition = FormStartPosition.CenterScreen;
            frm.ShowDialog();
            string email = frm.getEmail();
            txtFrom.Text = email;
            _nameFrom = frm.getName();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            ContactMail frm = new ContactMail();
            frm.ProjectPath = _projectPath;
            frm.StartPosition = FormStartPosition.CenterScreen;
            frm.ShowDialog();
            string email = frm.getEmail();
            txtTo.Text = email;
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            ContactMail frm = new ContactMail();
            frm.ProjectPath = _projectPath;
            frm.StartPosition = FormStartPosition.CenterScreen;
            frm.ShowDialog();
            string email = frm.getEmail();
            txtCc.Text += email + ";";
        }

        private void MailFrm_Load(object sender, EventArgs e)
        {
            if (!_sendPro)
            {
                foreach (string arr in _attachFiles)
                {
                    string item = Path.GetFileName(arr);
                    listBox1.Items.Add(item);
                }
            }
            else
            {

            }

            txtSub.ReadOnly = true;
            SetTextSub(txtSub_temp.Text);

            comboBox1.SelectedIndex = 0;
        }

        private bool bind = false;

        private bool _sendall = false;

        private bool _sendPro = false;


        public bool setSendAll
        {
            set { _sendall = value; }
        }

        public bool setSendPro
        {
            set { _sendPro = value; }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            int index = comboBox1.SelectedIndex;
            string follist = comboBox1.Items[index].ToString();

            string email;

            if (_sendPro)
            {
                string hour = DateTime.Now.ToShortTimeString();
                string arr = hour.Replace(':', '_');
                string desc = arr + "_" + "Email";

                this._childForm.SendToIssuedMail(follist, desc);
                email = this._childForm._manager.getEmailPath();
                _attachFiles1 = Directory.GetFiles(email, "*.*", SearchOption.AllDirectories);

                ////
                foreach (string arr1 in _attachFiles1)
                {
                    string item = Path.GetFileName(arr1);
                    listBox1.Items.Add(item);
                }
                bind = true;
                return;
            }
            //string desc = DateTime.Now.ToShortTimeString() + "_" + "Email";
            if (_sendall)
            {
                string hour = DateTime.Now.ToShortTimeString();
                string arr = hour.Replace(':', '_');
                string desc = arr + "_" + "Email";
                this._form.SendToIssuedMail(true, follist, desc);
                email = this._form.getEmailPath();
            }
            else
            {
                string hour = DateTime.Now.ToShortTimeString();
                string arr = hour.Replace(':', '_');
                string desc = arr + "_" + "Email";
                this._form.SendToIssuedMail(false, follist, desc);
                email = this._form.getEmailPath();
            }
            _attachFiles1 = Directory.GetFiles(email, "*.*", SearchOption.AllDirectories);
            bind = true;
        }

        private void txtSub_temp_KeyPress(object sender, KeyPressEventArgs e)
        {
            //ko fai enter
            if (e.KeyChar != 13)
            {

                string text;
                //ki tu xoa 1 ky tu
                if (e.KeyChar == 8)
                    text = txtSub_temp.Text.Remove(txtSub_temp.Text.Length - 1);
                else
                    text = txtSub_temp.Text + e.KeyChar;
                SetTextSub(text);
            }
        }

        private void SetTextSub(string text)
        {
            string name = Path.GetFileNameWithoutExtension(_projectPath);

            //string date = DateTime.Now.ToShortDateString();
            txtSub.Text = name + " | " + text + " | " + CodeNameUtilities.GetDateYYMMDD(DateTime.Now);
        }

    }
}